package com.fenghongzhang.day008view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;

public class FentText extends View {

    private static final String TAG = "FentText";
    float dimension;
    int color;
    String wenzi;
    int width;
    int height;
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    //java创建对象的时候
    public FentText(Context context) {
        super(context);
    }

    //在xml里引用的时候,会自动调用
    public FentText(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.FentText);
        wenzi = typedArray.getString(R.styleable.FentText_wenzi);
        dimension = typedArray.getDimension(R.styleable.FentText_daxiao, 30);
        color = typedArray.getColor(R.styleable.FentText_yanse, Color.RED);
        //释放资源
        typedArray.recycle();

    }


    //测量当前view的宽和高
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);


        //宽的测量模式
        int mode = MeasureSpec.getMode(widthMeasureSpec);
        int size = MeasureSpec.getSize(widthMeasureSpec);
        switch (mode){
            case MeasureSpec.EXACTLY:
                Log.i(TAG, "onMeasure: 0"+size);
                width = size;
                break;
            case MeasureSpec.AT_MOST:
                //得到文字的大长度 10,20 30
                width = 100;

                break;
            case MeasureSpec.UNSPECIFIED:
                Log.i(TAG, "onMeasure: 2"+size);
                break;
        }

        //高的测量模式
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        switch (mode){
            case MeasureSpec.EXACTLY:
                Log.i(TAG, "onMeasure: 0"+size);
                height = size;
                break;
            case MeasureSpec.AT_MOST:
                //得到文字的大长度 10,20 30
                height= 100;

                break;
            case MeasureSpec.UNSPECIFIED:
                Log.i(TAG, "onMeasure: 2"+size);
                break;
        }
        //设置具体的宽高
        setMeasuredDimension(width,height);

        /**
         *
         *  4 / 2 = 2
         *  00000001
         *  00000010
         *  00000100
         *  >>
         *  4 << 1
         *  00000010
         *
         */
    }

    //具体画出来你的值
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        paint.setTextSize(dimension);
        paint.setColor(color);
        canvas.drawText(wenzi,0,100,paint);

    }
}
